﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.ComponentModel;
using System.Xml;
using System.IO;
using System.Windows.Input;
using LiveCharts;
using LiveCharts.Wpf;

namespace MES90129;

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private DispatcherTimer timer;
    private List<DataItem> _dataItems = new List<DataItem>();
    private List<DataItem> _displayItems = new List<DataItem>();
    private ICommand _navigateCommand;
    private SeriesCollection _seriesCollection = new SeriesCollection();
    
    public event PropertyChangedEventHandler? PropertyChanged;
    
    public List<DataItem> DataItems
    {
        get { return _displayItems; }
        set
        {
            _displayItems = value;
            OnPropertyChanged("DataItems");
        }
    }
    
    public ICommand NavigateCommand
    {
        get
        {
            return _navigateCommand ?? (_navigateCommand = new RelayCommand(param => Navigate(Convert.ToInt32(param))));
        }
    }
    
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        LoadDataFromConfig();
        InitializeChartSeries();
        Navigate(1); // 默认显示第一页数据
        SetupTimer();
    }
    
    private void LoadDataFromConfig()
    {
        try
        {
            //string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.xml");
            //MessageBox.Show("当前工作目录：" + Directory.GetCurrentDirectory());
            string configPath = Directory.GetCurrentDirectory() + "\\config.xml";

            if (!File.Exists(configPath))
            {
                throw new FileNotFoundException("配置文件不存在");
            }
            
            XmlDocument doc = new();
            doc.Load(configPath);
            
            XmlNodeList? nodes = doc.SelectNodes("/DataConfig/DataItems/DataItem");
            if (nodes == null || nodes.Count == 0)
            {
                throw new Exception("配置文件格式不正确，缺少DataItem节点");
            }
            
            foreach (XmlNode node in nodes)
            {
                if (node.Attributes is null || node.Attributes["Name"] == null || node.Attributes["Unit"] == null)
                {
                    throw new Exception("DataItem节点缺少Name或Unit属性");
                }
                
                _dataItems.Add(new DataItem 
                { 
                    Name = node.Attributes["Name"]?.Value ?? string.Empty,
                    Value = 0, 
                    Unit = node.Attributes["Unit"]?.Value ?? string.Empty
                });
            }
            
            if (_dataItems.Count < 80)
            {
                throw new Exception($"配置文件数据不足，需要80个数据点，实际找到{_dataItems.Count}个");
            }
            
            OnPropertyChanged("DataItems");
        }
        catch (Exception ex)
        {
            MessageBox.Show($"加载配置文件失败: {ex.Message}\n将使用默认数据", "配置错误", MessageBoxButton.OK, MessageBoxImage.Warning);
            
            // 如果配置文件加载失败，使用默认数据
            _dataItems.Clear();
            for (int i = 0; i < 80; i++)
            {
                _dataItems.Add(new DataItem 
                { 
                    Name = "数据" + (i+1), 
                    Value = 0, 
                    Unit = "单位" 
                });
            }
        }
    }
    
    protected void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
    
    private void SetupTimer()
    {
        timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += (s, e) => UpdateData();
        timer.Start();
    }
    
    private void UpdateData()
    {
        Random rand = new Random();
        foreach (var item in _dataItems)
        {
            item.Value = rand.Next(0, 100);
        }
        OnPropertyChanged("DataItems");
    }
    
    private void Navigate(int page)
    {
        int startIndex = (page - 1) * 16;
        int endIndex = Math.Min(startIndex + 16, _dataItems.Count);
        
        _displayItems.Clear();
        for (int i = startIndex; i < endIndex; i++)
        {
            _displayItems.Add(_dataItems[i]);
        }
        
        UpdateChartSeries();
        OnPropertyChanged("DataItems");
    }
    
    private void InitializeChartSeries()
    {
        for (int i = 0; i < 8; i++)
        {
            _seriesCollection.Add(new LineSeries
            {
                Title = "Series " + (i+1),
                Values = new ChartValues<int>(),
                PointGeometry = null,
                LineSmoothness = 0
            });
        }
        
        OnPropertyChanged("SeriesCollection");
    }
    
    private void UpdateChartSeries()
    {
        for (int i = 0; i < 8; i++)
        {
            int dataIndex1 = i * 2;
            int dataIndex2 = i * 2 + 1;
            
            if (dataIndex2 < _displayItems.Count)
            {
                var series = _seriesCollection[i] as LineSeries;
                series.Values.Add(_displayItems[dataIndex1].Value);
                series.Values.Add(_displayItems[dataIndex2].Value);
                
                // 保持最多20个数据点
                if (series.Values.Count > 20)
                {
                    series.Values.RemoveAt(0);
                    series.Values.RemoveAt(0);
                }
            }
        }
    }
    
    public SeriesCollection SeriesCollection
    {
        get { return _seriesCollection; }
        set
        {
            _seriesCollection = value;
            OnPropertyChanged("SeriesCollection");
        }
    }
}

public class DataItem : INotifyPropertyChanged
{
    private string _name = string.Empty;
    private int _value;
    private string _unit = string.Empty;
    
    public event PropertyChangedEventHandler? PropertyChanged;
    
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }
    
    public int Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnPropertyChanged("Value");
        }
    }
    
    public string Unit
    {
        get { return _unit; }
        set
        {
            _unit = value;
            OnPropertyChanged("Unit");
        }
    }
    
    protected void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}